package com.example.nextstream.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.nextstream.mapper.UserMapper;
import com.example.nextstream.models.AssetsInfo;
import com.example.nextstream.models.User;
import com.example.nextstream.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Value("${sign.key}")
    private String signKey;

    //@Autowired
    //private UserMapper userMapper;

    @Override
    public String getToken(String username ,String  password){
        String token ="";

        Date date=new Date(); // get current time
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,30); //add 30 days !
        date=calendar.getTime();

        token = JWT.create().withAudience(this.getUserByName(username).getId().toString())  //设置为userid
                .withExpiresAt(date)         //指定token过期时间
				.sign(Algorithm.HMAC256(signKey));
        return token;
    }
    @Override
    public Boolean createUser(User user){
        baseMapper.insert(user);
        return true;
    }
    @Override
    public Boolean deleteUser(Integer userId){
        baseMapper.deleteById(userId);
        return true;
    }
    @Override
    public User getUserById(Integer id){
        return baseMapper.selectById(id);
    }

    @Override
    public Page<User> listUser(int pageNum, int pageSize) {
        Page<User> page= new Page<>(pageNum,pageSize);
        return baseMapper.selectPage(page,null);
    }

    @Override
    public Boolean updateUser(User user) {
        baseMapper.updateById(user);
        return true;
    }

    @Override
    public User getUserByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Integer countUser() {
        return baseMapper.selectCountUser();
    }
}
